package nio.tcp.server_client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class SocketChannelClient {

    public static void main(String[] args) throws IOException {

        //java7新语法，自动关闭流
        try (SocketChannel channel = SocketChannel.open(new InetSocketAddress("localhost", Server.listener_port))) {

            //		channel.connect(new InetSocketAddress("localhost", Server.listener_port));

            String sendData = "这里是nio客户端";
            ByteBuffer bb = ByteBuffer.allocate(Server.buffer_size);
            bb.put(ByteBuffer.wrap(sendData.getBytes()));

            bb.flip();
            while (bb.hasRemaining()) {
                channel.write(bb);
            }

            bb.clear();
            channel.read(bb);
            bb.flip();
            System.out.println("client接收到：" + Charset.forName("utf-8").newDecoder().decode(bb));
        }
    }
}
